package com.example.springboot.filter;

import com.example.springboot.config.ServiceException;
import com.example.springboot.domain.LoginUser;
import com.example.springboot.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    RedisTemplate<String, LoginUser> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException,IOException, ServiceException {
        //获取token
        String token = request.getHeader("Authorization");
        if(!StringUtils.hasText(token)){
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userid = null;
        try {
            Claims claims = JwtUtils.parseToken(token);
            userid=claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("400","token非法");
        }

        //从redis中获取用户信息
        String redisKey="login:"+userid;
        LoginUser user= redisTemplate.opsForValue().get(redisKey);
        if(Objects.isNull(user)){
            throw new ServiceException("400","用户未登录");
        }
        if(Boolean.FALSE.equals(redisTemplate.expire(redisKey,600000, TimeUnit.SECONDS))){
            throw new ServiceException("400","redis异常");
        }

        //存入securityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user,null, user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //放行
        filterChain.doFilter(request,response);
    }
}
